package com.hzncc.flowable_diboot.config;

import com.diboot.core.util.S;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.time.Duration;

@Log4j2
@Component
public class RequestInterceptor implements HandlerInterceptor {

    public static final Cache<String, String> REQUEST_CACHE = CacheBuilder.newBuilder()
            .maximumSize(10000)
            .expireAfterWrite(Duration.ofSeconds(20))
            .build();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("请求路径：" + request.getRequestURI() + "，请求方式：" + request.getMethod());
        String requestKey = request.getHeader("Authorization") + request.getRequestURI();
        String ifPresent = REQUEST_CACHE.getIfPresent(requestKey);
        if (S.isNotBlank(ifPresent)){
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write("{\"code\":\"400\",\"msg\":\"请求太频繁，请稍后再试\"}");
            log.info("请求拦截：" + requestKey);
            return false;
        }
        REQUEST_CACHE.put(requestKey, "1");
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        REQUEST_CACHE.invalidate(request.getHeader("Authorization") + request.getRequestURI());
    }
}
